package pl.edu.agh.to1.dice.logic;

import java.util.*;
import java.lang.String;
import java.io.*;

public abstract class RankingManager{
	private Comparator<RankingEntry> comparer;
	protected List<RankingEntry> entries;	

	public RankingManager(Comparator<RankingEntry> comparer){
		this.comparer = comparer;
		entries = new ArrayList<RankingEntry>();
	}		

	public String toString(){
		StringBuilder builder = new StringBuilder("");
		for(RankingEntry en : entries){
			builder.append(en.toString()).append("\n");
		}
		return builder.toString();	
	}

	protected void addEntry(RankingEntry en){
		entries.add(en);
	}

	public RankingEntry getRankingEntry(String name){
		RankingEntry entry = null;
		if(name == null | name==""){
			Random r = new Random();
			int i = r.nextInt() % 128;
			entry = new RankingEntry("Gamer"+i);
			entries.add(entry);
			onChangeEvent();
			return entry;
		}
		
		for(RankingEntry en : entries){
			if(en.getName().compareTo(name)==0)
				entry = en;
		}
		if(entry != null)
			return entry;
		entry = new RankingEntry(name);
		entries.add(entry);
		onChangeEvent();
		return entry;
	}

	public void update(){
		onChangeEvent();
	}

	public void onClose(){
		save();
	}

	public void reset(){
		entries.clear();
	}

	private void onChangeEvent(){
		Collections.sort(entries,comparer);
	}

	public abstract void load();
	protected abstract void save();
}
